layui.define(['form', 'laytpl', 'staticData', 'autocomplete','upload','supplier','takeInformation','deliveryInformation','uploadList'], function (exports) {
    var $ = layui.$, com = layui.com, request = layui.request,search = layui.router().search,uploadList = layui.uploadList,
        form = layui.form, upload = layui.upload,supplier = layui.supplier,takeInformation = layui.takeInformation,deliveryInformation = layui.deliveryInformation,
        staticData = layui.staticData, autocomplete = layui.autocomplete,
        $quantityTotal = $('#quantityTotal'), $totalPriceTotal = $('#totalPrice'),
        $cartonTotal = $('#cartonTotal'), $netWeightTotal = $('#netWeightTotal'),
        $grossWeightTotal = $('#grossWeightTotal'),fileId = 'temp_' + com.uuid(),fn = {
            impQuotes: {}// 协议报价
            // 生成订单编号
            ,
            async generateImpOrderNo() {
                await request.postForm('/scm/serialNumber/generateDocNo', {
                    type: 'imp_order'
                }).then(res => {
                    $('#docNo').val(res.data);
                });
            }
            // 获取协议报价
            ,
            async getAgreement(defBtVal, defIqVal, defTmVal) {
                await request.get('/scm/client/agreement/impAgreement').then(res => {
                    let data = res.data;
                    if (data && data.length > 0) {
                        var $businessType = $('#businessType');
                        $businessType.get(0).length = 0;
                        if (data.length > 1) {
                            $businessType.append('<option value="">请选择</option>');
                        }
                        $.each(data, function (i, o) {
                            $businessType.append('<option value="' + o.businessType + '" ' + (o.businessType == defBtVal ? ' selected ' : '') + '>' + o.businessTypeName + '</option>');
                            fn.impQuotes[o.businessType] = {
                                "quotes": o.quotes,
                                "transactionMode": o.transactionMode,
                                "declareType": o.declareType,
                                "declareTypeName": o.declareTypeName
                            };
                        });
                        fn.fullImpQuote(defIqVal, defTmVal);
                    }
                }).catch((err)=>{
                    layer.closeAll();
                    let idx = com.alertWarn(err.message,function () {
                        layer.close(idx);
                        location.hash = '/company/agreement';
                    });
                });
            }
            // 填充协议报价
            ,
            fullImpQuote(defIqVal, defTmVal) {
                var businessType = $('#businessType').val(), $impQuoteId = $('#impQuoteId');
                $impQuoteId.get(0).length = 0;
                if (com.isNotEmpty(businessType)) {
                    var impAgreement = fn.impQuotes[businessType];
                    $.each(impAgreement.quotes || [], function (i, o) {
                        $impQuoteId.append('<option value="' + o.id + '" ' + (o.id == defIqVal ? ' selected ' : '') + '>' + o.memo + '</option>');
                    });
                    //成交方式
                    fn.initTransactionMode(impAgreement.transactionMode, defTmVal);
                    //报关类型
                    $('#declareTypeName').val(impAgreement.declareTypeName);
                }
                form.render(null, 'form-order-base');
            }
            // 初始化成交方式
            ,
            async initTransactionMode(optionalVal, defaultVal) {
                var transactionModeData = await staticData.getTransactionModeData(),
                    $transactionMode = $('#transactionMode');
                $transactionMode.get(0).length = 0;
                if (com.isEmpty(optionalVal)) {
                    $transactionMode.append('<option value="">请选择</option>');
                }
                $.each(transactionModeData || [], function (i, o) {
                    if (com.isEmpty(optionalVal) || (com.isNotEmpty(optionalVal) && optionalVal == o.value)) {
                        $transactionMode.append('<option value="' + o.value + '" ' + ((com.isNotEmpty(defaultVal) && defaultVal == o.value) ? ' selected ' : '') + '>' + o.label + '</option>');
                    }
                });
                form.render(null, 'form-order-base');
            }
            // 初始化币制数据
            ,
            async initCurrency() {
                var currencyData = await staticData.getCurrencyData();
                autocomplete.render({
                    elem: $("#order-add-currency-name"),
                    template_txt: '{{d.label}}',
                    template_val: '{{d.label}}',
                    result: currencyData,
                    onselect: function (data) {
                        fn.thisMonthRate(data.value);
                    }
                });
            }
            // 根据币制获取汇率
            ,
            thisMonthRate(currencyId) {
                var $showCustomsRate = $('#add-order-show-rate');
                $showCustomsRate.hide();
                if (com.isNotEmpty(currencyId)) {
                    request.postForm('/system/customsRate/thisMonth', {'currencyId': currencyId}).then(res => {
                        $showCustomsRate.html('海关汇率：' + (res.data || '')).show();
                    });
                }
            }
            // 添加一行明细
            ,
            createRow(mid, goodsModel, goodsName, goodsBrand, unitName, quantity, unitPrice, totalPrice, cartonNum, netWeight, grossWeight, countryName, goodsCode, goodsSpec) {
                $('#materialBody').append(fn.createRowHtml(mid, goodsModel, goodsName, goodsBrand, unitName, quantity, unitPrice, totalPrice, cartonNum, netWeight, grossWeight, countryName, goodsCode, goodsSpec));
                fn.createIndex();
                fn.autoMemberVague();
            }
            ,createRows(members){
                var mhtml = [],tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
                $.each(members,function (i,o) {
                    mhtml.push(fn.createRowHtml(o.id,o.model,o.name,o.brand,o.unitName,o.quantity,o.unitPrice,o.totalPrice,o.cartonNum,o.netWeight,o.grossWeight,o.countryName,o.goodsCode,o.spec));
                    tquantity+=o.quantity;ttotalPrice+=o.totalPrice;tcartonNum+=o.cartonNum;tnetWeight+=o.netWeight;tgrossWeight+=o.grossWeight;
                });
                $('#materialBody').append(mhtml.join(''));
                $quantityTotal.html(Math.round(tquantity*100)/100);
                $totalPriceTotal.html(com.formatCurrency(Math.round(ttotalPrice*100)/100));
                $cartonTotal.html(tcartonNum);
                $netWeightTotal.html(Math.round(tnetWeight*10000)/10000);
                $grossWeightTotal.html(Math.round(tgrossWeight*10000)/10000);
                fn.createIndex();
                fn.calculationAll();
                fn.autoMemberVague();
            }
            // 构建明细
            ,
            createRowHtml(mid, goodsModel, goodsName, goodsBrand, unitName, quantity, unitPrice, totalPrice, cartonNum, netWeight, grossWeight, countryName, goodsCode, goodsSpec) {
                return [
                    '<tr><td class="t-a-c mindex"></td>',
                    '<td><input type="hidden" name="id" LIST value="' + (com.isEmpty(mid) ? '' : mid) + '"/><input type="text" name="model" LIST class="layui-input required add-order-auto-materiel-model" placeholder="支持模糊搜索" value="' + (com.isEmpty(goodsModel) ? '' : goodsModel) + '"/></td>',
                    '<td><input type="text" name="name" LIST class="layui-input add-order-auto-materiel-name" placeholder="支持模糊搜索" value="' + (com.isEmpty(goodsName) ? '' : goodsName) + '"/></td>',
                    '<td><input type="text" name="brand" LIST class="layui-input required add-order-auto-materiel-brand" placeholder="支持模糊搜索" value="' + (com.isEmpty(goodsBrand) ? '' : goodsBrand) + '"/></td>',
                    '<td><input type="text" name="unitName" LIST class="layui-input required add-order-member-unit" value="' + (com.isEmpty(unitName) ? '个' : unitName) + '"/></td>',
                    '<td><input type="text" name="quantity" LIST onblur="layui.orderManage.calculationAll(this)" NUMBER CLEARZERO class="layui-input required" value="' + (com.isEmpty(quantity) ? '' : quantity) + '"/></td>',
                    '<td><input type="text" name="unitPrice" LIST class="layui-input layui-disabled" readonly value="' + (com.isEmpty(unitPrice) ? '0' : unitPrice) + '"/></td>',
                    '<td><input type="text" name="totalPrice" LIST onblur="layui.orderManage.calculationAll(this)" NUMBER CLEARZERO class="layui-input required" value="' + (com.isEmpty(totalPrice) ? '' : totalPrice) + '"/></td>',
                    '<td><input type="text" name="cartonNum" LIST onblur="layui.orderManage.calculationAll()" INT CLEARZERO class="layui-input required" value="' + (com.isEmpty(cartonNum) ? '0' : cartonNum) + '"/></td>',
                    '<td><input type="text" name="netWeight" LIST NUMBER="4" CLEARZERO onblur="layui.orderManage.calculationAll()" class="layui-input required" value="' + (com.isEmpty(netWeight) ? '0' : netWeight) + '"/></td>',
                    '<td><input type="text" name="grossWeight" LIST NUMBER="4" CLEARZERO onblur="layui.orderManage.calculationAll()" class="layui-input required" value="' + (com.isEmpty(grossWeight) ? '0' : grossWeight) + '"/></td>',
                    '<td><input type="text" name="countryName" LIST class="layui-input required add-order-member-country" value="' + (com.isEmpty(countryName) ? '中国' : countryName) + '"/>',
                    '<input type="hidden" name="goodsCode" LIST class="layui-input" value="' + (com.isEmpty(goodsCode) ? '' : goodsCode) + '"/>',
                    '<input type="hidden" name="spec" LIST class="layui-input" value="' + (com.isEmpty(goodsSpec) ? '' : goodsSpec) + '"/></td>',
                    '<td class="t-a-c"><a href="javascript:" zmark-event="layui.orderManage.removeRow" title="删除"><i class="iconfont iconhuishou f14"></i></a></td></tr>'
                ].join('');
            }
            ,
            removeRow(othis) {
                var $per = othis.parent().parent();
                $per.remove();
                fn.createIndex();
                fn.calculationAll();
            }
            ,
            createIndex() {
                var mind = 1;
                $.each($('.mindex'), function (i, o) {
                    $(o).html(mind++);
                });
            }
            // 计算统计
            ,
            calculationAll(e) {
                var tquantity = 0.0, ttotalPrice = 0.0, tcartonNum = 0, tnetWeight = 0.0, tgrossWeight = 0.0;
                if (com.isNotEmpty(e)) {
                    var $that = $(e), $parent = $that.parent().parent(), $quantity = $parent.find('input[name="quantity"]'),
                        $unitPrice = $parent.find('input[name="unitPrice"]'),
                        $totalPrice = $parent.find('input[name="totalPrice"]');
                    switch ($that.attr('name')) {
                        case 'quantity':
                            var quantity = Math.round(parseFloat($quantity.val() || '0.0') * 100) / 100;
                            var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0') * 100) / 100;
                            $unitPrice.val(Math.round(totalPrice / quantity * 10000) / 10000);
                            break;
                        case 'unitPrice':
                            var quantity = Math.round(parseFloat($quantity.val() || '0.0') * 100) / 100;
                            var unitPrice = Math.round(parseFloat($unitPrice.val() || '0.0') * 10000) / 10000;
                            $totalPrice.val(Math.round(quantity * unitPrice * 100) / 100);
                            break;
                        case 'totalPrice':
                            var quantity = Math.round(parseFloat($quantity.val() || '0.0') * 100) / 100;
                            if (quantity == 0.0) {
                                $unitPrice.val('0.0000');
                                return;
                            }
                            var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0') * 100) / 100;
                            $unitPrice.val(Math.round(totalPrice / quantity * 10000) / 10000);
                            break;
                    }
                }
                $.each($('#materialBody').find('tr'), function (i, o) {
                    var $that = $(o);
                    tquantity += Math.round(parseFloat($that.find('input[name="quantity"]').val() || '0.0') * 100) / 100;
                    ttotalPrice += Math.round(parseFloat($that.find('input[name="totalPrice"]').val() || '0.0') * 100) / 100;
                    tcartonNum += parseInt($that.find('input[name="cartonNum"]').val() || '0');
                    tnetWeight += Math.round(parseFloat($that.find('input[name="netWeight"]').val() || '0.0') * 10000) / 10000;
                    tgrossWeight += Math.round(parseFloat($that.find('input[name="grossWeight"]').val() || '0.0') * 10000) / 10000;
                });
                $quantityTotal.html(Math.round(tquantity * 100) / 100);
                $totalPriceTotal.html(com.formatCurrency(Math.round(ttotalPrice * 100) / 100));
                $cartonTotal.html(tcartonNum);
                $netWeightTotal.html(Math.round(tnetWeight * 10000) / 10000);
                $grossWeightTotal.html(Math.round(tgrossWeight * 10000) / 10000);
            }
            ,async autoMemberVague(){
                var unitData = await staticData.getUnitData(),countryData = await staticData.getCountryData();
                $('#materialBody').find('tr').each(function (i,o) {
                    var othis = $(o),$model = othis.find('.add-order-auto-materiel-model'),$name=othis.find('.add-order-auto-materiel-name'),$brand=othis.find('.add-order-auto-materiel-brand'),
                        $unit=othis.find('.add-order-member-unit'),$country=othis.find('.add-order-member-country');
                    if($model.length>0){
                        autocomplete.render({
                            elem: $model,
                            url: '/scm/client/materiel/vague',
                            template_txt: '型号：{{d.model}} 名称：{{d.name}} 品牌：{{d.brand}}',
                            template_val: '{{d.model}}',
                            ajaxParams: {
                                type: 'post',contentType: 'application/x-www-form-urlencoded'
                            },
                            request: {
                                keywords: 'model'
                            },
                            onselect:function (data) {
                                othis.find('input[name="name"]').val(data.name);
                                othis.find('input[name="brand"]').val(data.brand);
                                othis.find('input[name="spec"]').val(data.spec || '');
                            }
                        });
                        $model.removeClass('add-order-auto-materiel-model');
                    }
                    if($name.length>0){
                        autocomplete.render({
                            elem: $name,
                            url: '/scm/client/materiel/vague',
                            template_txt: '名称：{{d.name}} 型号：{{d.model}} 品牌：{{d.brand}}',
                            template_val: '{{d.name}}',
                            ajaxParams: {
                                type: 'post',contentType: 'application/x-www-form-urlencoded'
                            },
                            request: {
                                keywords: 'name'
                            },
                            onselect:function (data) {
                                othis.find('input[name="model"]').val(data.model);
                                othis.find('input[name="brand"]').val(data.brand);
                                othis.find('input[name="spec"]').val(data.spec || '');
                            }
                        });
                        $model.removeClass('add-order-auto-materiel-name');
                    }
                    if($brand.length>0){
                        autocomplete.render({
                            elem: $brand,
                            url: '/scm/client/materiel/vagueByBrand',
                            template_txt: '{{d}}',
                            template_val: '{{d}}',
                            ajaxParams: {
                                type: 'post',contentType: 'application/x-www-form-urlencoded'
                            },
                            request: {
                                keywords: 'brand'
                            }
                        });
                        $model.removeClass('add-order-auto-materiel-brand');
                    }
                    if($unit.length>0){
                        autocomplete.render({
                            elem: $unit,
                            template_txt: '{{d.label}}',
                            template_val: '{{d.label}}',
                            result: unitData
                        });
                        $model.removeClass('add-order-member-unit');
                    }
                    if($country.length>0){
                        autocomplete.render({
                            elem: $country,
                            template_txt: '{{d.label}}',
                            template_val: '{{d.label}}',
                            result: countryData
                        });
                        $model.removeClass('add-order-member-country');
                    }
                });
            }
            // 获取订单详情
            ,async detail(id,operation){
                let data = {order:{businessType:'',impQuoteId:'',transactionMode:''},logistiscs:{
                        deliveryMode:'GiveDelivery'
                        ,hkExpress:'HK_SF',supplierTakeInfoId:null,logisticsCompanyId:null,prescription:'',customerDeliveryInfoId:null,
                        receivingMode:'ThirdLogistics',selfWareId:''
                    },members:[]};
                if(com.isNotEmpty(id)){
                    await request.postForm('/scm/impOrder/detail',{id:id,operation:operation}).then(res =>{
                        data = res.data;
                        // 审核意见
                        if(com.isNotEmpty(data.order.auditOpinion)){
                            $('#order-audit-opinion-tips').show().find('p').html(data.order.auditOpinion);
                        }
                    }).catch(()=>{
                        location.hash = '/order/list';
                    });
                }
                return data;
            }
            ,async initBaseData(logistiscs){
                // 供应商模糊查询
                autocomplete.render({
                    elem: $("#order-add-supplier-name"),
                    url: '/scm/client/supplier/vague',
                    template_txt: '{{d.name}}',
                    template_val: '{{d.name}}',
                    ajaxParams: {
                        type: 'post',
                        contentType: 'application/x-www-form-urlencoded'
                    },
                    request: {
                        keywords: 'name'
                    },
                    onselect:function (da) {
                        fn.takeInformation();
                    }
                });
                // 币制
                fn.initCurrency();
                // 导入明细解析
                upload.render({
                    elem: '#add-order-import-member',url:'/scm/impOrder/importMember',size:10240,exts:'xls|xlsx'
                    ,acceptMime:'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    ,before:function (res) {
                        com.showLoading();
                    },done: function(res){
                        if(com.isSuccessWarn(res)){
                            var memberData = res.data;
                            layer.msg("成功导入："+memberData.length+" 条数据");
                            $('input[name="model"]').each(function (i,o) {
                                var $model = $(o);if(com.isEmpty($model.val())){$model.parent().parent().remove();}
                            });
                            fn.createRows(memberData);
                        }
                    },error:function (index, upload) {
                        com.hideLoading();
                    }
                });
                // 境外交货方式
                let deliveryModes = await staticData.getDeliveryMode(),$deliveryMode = $('#deliveryMode');
                com.fullSelect({
                    elem:$deliveryMode,
                    data:deliveryModes,
                    defValue:logistiscs.deliveryMode
                });
                fn.showOrHide($deliveryMode);
                // 加载提货地址
                if(com.isNotEmpty($('#order-add-supplier-name').val())&&'TakeDelivery'==logistiscs.deliveryMode){
                    await fn.takeInformation(logistiscs.supplierTakeInfoId);
                }
                // 香港快递
                let hkExpresss = await staticData.getHkExpress(),$hkExpress = $('#hkExpress');
                com.fullSelect({
                    elem:$hkExpress,
                    data:hkExpresss,
                    defValue:logistiscs.hkExpress
                });

                // 国内送货方式
                let receivingModes = await staticData.getReceivingMode(),$receivingMode = $('#receivingMode');
                com.fullSelect({
                    elem:$receivingMode,
                    data:receivingModes,
                    defValue:logistiscs.receivingMode
                });
                fn.showOrHide($receivingMode);
                // 物流公司
                let domesticLogistics = await staticData.getDomesticLogistics(),$logisticsCompany = $('#logisticsCompany');
                com.fullSelect({
                    elem:$logisticsCompany,
                    data:domesticLogistics,
                    label:'name',
                    value:'id',
                    defValue:logistiscs.logisticsCompanyId
                });
                // 物流时效
                await fn.logisticsTimeliness(logistiscs.prescription);
                // 国内收货地址信息
                await fn.deliveryInformation(logistiscs.customerDeliveryInfoId);
                // 自提仓库
                await fn.initTakeSelfWare(logistiscs.selfWareId);

            }
            // 初始化自提仓库信息
            ,async initTakeSelfWare(defVal){
                let wares = await staticData.getTakeSelfWare(),$selfWare = $('#selfWare');
                com.fullSelect({
                    elem:$selfWare,
                    data:wares,
                    value:'id',
                    label:'detailDesc',
                    defValue:defVal || ''
                })
            }
            // 物流时效展示
            ,async logisticsTimeliness(defLtVal){
                let logisticsCompanyId = $('#logisticsCompany').val(),$askContainer=$('#askContainer'),domesticLogistics = await staticData.getDomesticLogistics(),
                    bhtml = [];
                domesticLogistics.some(o =>{
                    if(logisticsCompanyId==o.id){
                        (o.timeline || []).forEach(t=>{
                            if(com.isEmpty(defLtVal)){defLtVal=t;}
                            bhtml.push('<input type="radio" name="prescription" value="'+t+'" title="'+t+'" '+(t==defLtVal?'checked':'')+'/>');
                        });
                        return true;
                    }
                });
                $askContainer.html(bhtml.join(''));
                form.render('radio', 'form-order-logistics');
            }
            ,showOrHide(othis) {
                var $mark = $('[mark="'+othis.attr('id')+'"]');
                $mark.hide();
                $.each($mark,function (j,k) {
                    var zmkeys = $(k).attr('zm-key').split(",");
                    if(com.contain(zmkeys,othis.val())){
                        $(k).show();
                    }
                });
            }
            // 获取供应商提货地址
            ,takeInformation(defVal){
                let $supplierName = $('#order-add-supplier-name');
                if(com.isEmpty($supplierName.val())){
                    layer.msg('请先选择境外供应商');
                    $supplierName.focus();
                    return;
                }
                var takeInformationsObj = $('#takeInformations');
                takeInformationsObj.html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>');
                request.postForm('/scm/client/supplierTakeInfo/page',{limit:100,supplierName:$supplierName.val(),disabled:false}).then(res =>{
                    var thtml = [];
                    $.each((res.data || []),function (i,o) {
                        if(com.isEmpty(defVal)){defVal = o.id;}
                        thtml.push('<div class="range-list-item"><input type="radio" name="supplierTakeInfoId" value="'+o.id+'" title="【'+o.companyName+'】'+o.provinceName+o.cityName+o.areaName+o.address+' ('+o.linkPerson+' '+o.linkTel+')" '+(o.id==defVal?'checked="true"':'')+'/><div class="right-edit"><a href="javascript:" title="修改" onclick="layui.orderManage.takeInformationManage(\''+o.id+'\')"><i class="iconfont iconB"></i></a></div></div>');
                    });
                    takeInformationsObj.html(thtml.join(""));
                    form.render('radio','form-order-logistics');
                });
            }
            // 获取客户收货地址
            ,async deliveryInformation(defDiVal){
                var deliveryInformationsObj = $('#deliveryInformations');
                deliveryInformationsObj.html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>');
                await request.get('/scm/client/customerDeliveryInfo/effectiveList').then(res =>{
                    var thtml = [];
                    $.each((res.data || []),function (i,o) {
                        if(com.isEmpty(defDiVal)){defDiVal=o.id;}
                        thtml.push('<div class="range-list-item"><input type="radio" name="customerDeliveryInfoId" value="'+o.id+'" title="【'+o.companyName+'】'+o.provinceName+o.cityName+o.areaName+o.address+' ('+o.linkPerson+' '+o.linkTel+')" '+(o.id==defDiVal?'checked="true"':'')+'/><div class="right-edit"><a href="javascript:" title="修改" onclick="layui.orderManage.deliveryInformationManage(\''+o.id+'\')"><i class="iconfont iconB"></i></a></div></div>');
                    });
                    deliveryInformationsObj.html(thtml.join(""));
                    form.render('radio','form-order-logistics');
                });
            }
            ,supplierManage(){
                supplier.add(function (sup) {
                    form.val('form-order-base', {'supplierId': sup.id, 'supplierName': sup.name});
                    fn.takeInformation();
                });
            }
            ,takeInformationManage(id){
                takeInformation.show(id,$('#order-add-supplier-name').val(),function (tim) {
                    if(com.isNotEmpty($('#order-add-supplier-name').val())){
                        fn.takeInformation();
                    }
                });
            }
            ,deliveryInformationManage(id){
                deliveryInformation.show(id,function (tim) {
                    fn.deliveryInformation();
                });
            }
            ,async init(){
                let detail = await fn.detail(search.id,com.isNotEmpty(search.copy)?'':'order_edit'),
                    order = detail.order,members=detail.members,logistiscs=detail.logistiscs;
                // 复制订单
                if(com.isNotEmpty(search.copy)){order.id='';}
                form.val('form-order-base',order);
                form.val('form-order-logistics',logistiscs);
                $('#memo').val(order.memo||'');
                // 获取协议
                await fn.getAgreement(order.businessType,order.impQuoteId,order.transactionMode);
                // 海关汇率
                if(com.isNotEmpty(order.currencyId)){
                    fn.thisMonthRate(order.currencyId);
                }
                // 产品明细数据
                if(members&&members.length>0){
                    fn.createRows(members);
                }else{
                    fn.createRow();
                }
                await fn.initBaseData(logistiscs);
                if(com.isEmpty(order.id)){
                    await fn.generateImpOrderNo();
                }else{
                    fileId = order.id;
                }
                $('.upload-box').attr({'file-id': fileId, 'edit': 'true'});
                uploadList.init();
                form.render(null, 'form-order-base');
                form.render(null, 'form-order-logistics');

                $('#temporarySave').click(function () {
                    fn.save(false);
                });
                $('#submitSave').click(function () {
                    fn.save(true);
                });
            }
            //订单明细数据
            ,obtainMenberJSON() {
                var members = [],orderMember = $('#orderMemberForm').serializeJson(),keys=[];
                for(var key in orderMember){keys.push(key);}
                $.each(orderMember[keys[0]] ||[],function (i,o) {
                    var item = {};
                    $.each(keys,function (j,k) {
                        item[k] = orderMember[k][i];
                    });
                    members.push(item);
                });
                return members;
            }
            // 保存订单
            ,save(submit){
                if(!com.validateForm($('#orderMainForm'))){return;}
                var order = $('#orderMainForm').serializeJson(),logistiscs =  $('#orderLogisticsForm').serializeJson(),members = fn.obtainMenberJSON(),
                    fileObj = {docId:fileId, docType:'imp_order'};
                order['memo'] = $('#memo').val();//备注
                com.showLoading();
                request.post('/scm/client/impOrder/'.concat(com.isNotEmpty(order.id)?'edit':'add'),{
                    "order":order,"logistiscs":logistiscs,"members":members,"submitAudit":submit,"file":fileObj
                }).then(res =>{
                    $('.sub-order-btn').off('click');
                    let orderId = res.data || order.id;
                    layer.msg('保存成功',{time: 1200},function () {
                        if(submit){
                            location.hash = '/order/success/id='+orderId+'/docNo='+order.docNo;
                        }else{
                            location.hash = '/order/list';
                        }
                    });
                });
            }
        }
    ;
    // 监听业务类型选择
    form.on('select(select-order-business-type)', function () {
        fn.fullImpQuote();
    });
    // 监听交货方式
    form.on('select(select-add-order-delivery-mode)',function (da) {
        fn.showOrHide($(da.elem));
    });
    // 监听送货方式
    form.on('select(select-add-order-receiving-mode)',function (da) {
        fn.showOrHide($(da.elem));
    });
    // 监听国内物流选择
    form.on('select(select-add-order-logistics-company)',function (da) {
       fn. logisticsTimeliness();
    });
    fn.init();
    exports('orderManage', fn);
});